(function(window, css_url, undefined) {
'use strict';

// #[function("createLink", "添加link")]
// #[param("url", "css地址")]
function createLink(url) {
    if (!url) return;

    var link = document.createElement("link");
    link.setAttribute("rel", "stylesheet");
    link.setAttribute("type", "text/css");
    link.setAttribute("href", url);

    var heads = document.head || document.getElementsByTagName('head')[0];

    heads.appendChild(link);
}

// #[function("createElem", "创建元素")]
// #[param1("elemName", "创建元素节点的名称")]
// #[param2("appendElem", "追加在那个元素里面")]
// #[return("返回创建的元素节点")]
function createElem(elemName, appendElem) {
    if (!elemName) return;

    var elem = document.createElement(elemName); // 创建元素节点
    if (appendElem) {
        appendElem.appendChild(elem);
    }else{
        document.body.appendChild(elem);
    }

    return elem;
}

// #[function("removeElem", "删除元素节点")]
// #[param1("elemName", "删除元素节点名称")]
function removeElem(elemName) {
    if (!elemName) return;
    elemName.remove();
}

// #[function("setStyle", "设置 元素 的 style")]
// #[param1("elem", "给那个元素添加样式")]
// #[param1("style", "样式表")]
function setStyle(elem, style = {}) {
    if (!elem) return;

    for (var val in style) {
        elem.style[val] = style[val];
    }
}

// #[function("getStyle", "获取元素的属性值 getComputedStyle",
//     "getComputedStyle 的第二个参数 是获取伪元素的样式表")]
// #[param1("obj elem", "元素")]
// #[param2("str prop", "样式属性名 eg: width")]
// #[return("返回属性值")]
function getStyle(elem, prop) {
    if (window.getComputedStyle) {
        return window.getComputedStyle(elem, null)[prop];
    }else{
        return elem.currentStyle[prop];
    }
}

// #[function("addEvent", "封装事件处理函数 解决兼容性问题")]
// #[param1("obj elem", "绑定在谁身上")]
// #[param2("str type", "事件类型")]
// #[param3("fun handle", "事件处理函数")]
function addEvent(elem, type, handle) {
    if (elem.addEventListener) {
        elem.addEventListener(type, handle, false);
    }else if(elem.attachEvent) {
        elem.attachEvent('on' + type, handle);
    }else{
        elem['on' + type] = handle;
    }
}

// 加载 css
(function() {
    if (!css_url) {
        return console.log('css url not null');
    }
    createLink(css_url);
}());

    var Layer = function(options) {
        var that = this;

        // 客户端
        that.ifmob = /Android|webOS|iPhone|iPad|BlackBerry/i.test(navigator.userAgent);

        // 主id
        var rand = Math.random().toString().split('.')[1];
        var mainid = 'layer_'+rand;
        that.mainid = mainid;


        // options
        var options = that.namefix(options);
        that.options = options;

        // call back fun
        that.callBackFun(that, options);

        // // 关闭
        // if (options.model === 'close') {
        //     that.close(options.closeid);
        //     return false;
        // }

        // // 关闭所有
        // if (options.model === 'closeAll') {
        //     that.closeAll();
        //     return false;
        // }

        // console.log(options);

        //入口
        that.creat();
    };

    Layer.parent = Layer.prototype;

    // 参数名称补全
    Layer.parent.namefix = function(options) {
        // 方位
        if (options.offset) {
            options.offset = options.offset.toLowerCase();
            if (options.offset === 't') {
                options.offset = 'top';
            }else if (options.offset === 'r') {
                options.offset = 'right';
            }else if (options.offset === 'b') {
                options.offset = 'bottom';
            }else if (options.offset === 'l') {
                options.offset = 'left';
            }else if(options.offset === 'm') {
                options.offset = 'middle';
            }
        }

        // 类型
        if (options.type) {
            options.type = parseInt(options.type);
            if(options.type === 1) {
                options.type = 'black';
            }else if(options.type === 2) {
                options.type = 'white';
            }else if (options.type === 'r') {
                options.type = 'ready';
            }else if (options.type === 'n') {
                options.type = 'noready';
            }else if (options.type === 'u') {
                options.type = 'url';
            }else if (options.type === 'h') {
                options.type = 'html';
            }else if(options.type === 'p') {
                options.type = 'photo';
            }else if(options.type === 'a') {
                options.type = 'alert';
            }else if(options.type === 'c') {
                options.type = 'confirm';
            }
        }

        // 图标
        if (options.icon) {
            if (typeof(options.icon) === 'object') {
                options.icon = options.icon[0];
            }
            options.icon = parseInt(options.icon);
            options.icon_flag = true;
            if (options.icon === 1) {
                options.icon = 'success';
            }else if (options.icon === 2) {
                options.icon = 'error';
            }else if (options.icon === 3) {
                options.icon = 'warning';
            }else if (options.icon === 4) {
                options.icon = 'ask';
            }else if (options.icon === 5) {
                options.icon = 'hello';
            }
            if (options.icon !== 'success' &&
                options.icon !== 'error' &&
                options.icon !== 'warning' &&
                options.icon !== 'ask' &&
                options.icon !== 'hello') {
                options.icon_flag = false;
            }
        }

        // // 文字对齐
        // if (options.align) {
        //     options.align = options.align.toLowerCase();
        //     if (options.align === 'l') {
        //         options.align = 'left';
        //     }else if (options.align === 'c') {
        //         options.align = 'center';
        //     }else if (options.align = 'r') {
        //         options.align = 'right';
        //     }
        // }
        return options;
    };

    // 回调函数
    Layer.parent.callBackFun = function(that, options) {
        if (options.end) {
            if (typeof(options.end) === "function") {
                that.end = options.end;
            }
        }
        if (options.yes) {
            if (typeof(options.yes) === "function") {
                that.yes = options.yes;
            }
        }
        if (options.cancel) {
            if (typeof(options.cancel) === "function") {
                that.cancel = options.cancel;
            }
        }
    };

    // 入口
    Layer.parent.creat = function () {
        var that = this,
            options = that.options;

        // 1. 构建内部html
        var html = that.html(options);
        if(!html){
            return false;
        }

        // 2. 创建元素 设置id 将layer追加到body中
        that.layer_main = that.createLayerElem(that.mainid, html);

        // 3. add classname, attr
        that.attr(that.layer_main, options);

        // 4. 添加动画效果
        that.on(that.layer_main);

        // 5. 后续处理
        that.after(that, that.layer_main, options);
    }

    // 1. create html
    Layer.parent.html = function (options) {
        var html = '';

        // 短消息
        if (options.model === 'msg') {
            html += '<p>';

            if (options.icon) {
                var i_html = '';
                if (options.icon === 'success') {
                    i_html = '<i class="layer-iconfont layer-icon-'+ options.icon +'">&#xe605;</i>';
                } else if (options.icon === 'error') {
                    i_html = '<i class="layer-iconfont layer-icon-'+ options.icon +'">&#xe600;</i>';
                }
                html += options.icon_flag === true ? i_html : '';
            }

            html += options.content + '</p>';
        } else if (options.model === 'confirm') {
            html += '<div class="layer-bg"></div>';

            html += '<div class="layer-main layer-confirm">';

            html += '    <div class="layer-confirm-title">';
            html += '        <p>'+ options.title +'</p>';
            html += '        <i class="layer-iconfont close">&#xe6c9;</i>';
            html += '    </div>';

            html += '    <div class="layer-confirm-content">';
            html +=          options.content;
            html += '    </div>';

            html += '<div class="layer-confirm-btn">';

            var btn_0, btn_1;
            if (typeof(options.btn) === 'object') {
                btn_0 = options.btn[0] ? options.btn[0] : '确定';
                btn_1 = options.btn[1] ? options.btn[1] : '取消';
            }else{
                btn_0 = '确定';
                btn_1 = '取消';
            }

            html += '    <button class="btn0 yes">'+ btn_0 +'</button>';
            html += '    <button class="btn1 cancel">'+ btn_1 +'</button>';
            html += '</div>';

            html += '</div>';
        }

        return html;
    }

    // 2. create layer elem, set id, Append layer to body
    Layer.parent.createLayerElem = function (mainid, html) {
        var main_elem = createElem('div');

        main_elem.setAttribute('id', mainid);
        main_elem.classList.add('layer');
        main_elem.innerHTML = html;

        var layer_main = document.getElementById(mainid);
        return layer_main;
    }

    // 3. add classname, attr
    Layer.parent.attr = function (layer_main, options) {
        var layerElemCenter = function (elem) {
            var elem_w = elem.offsetWidth,
                elem_t = elem.offsetHeight;
            setStyle(elem, {
                'margin-left': (-parseInt(elem_w) / 2) + 'px',
            });
        }

        // 短消息
        if (options.model === 'msg') {
            layer_main.classList.add('layer-msg');
            layer_main.classList.add('layer-msg-' + options.offset);
            layer_main.classList.add('layer-msg-' + options.type);
            setStyle(layer_main, {'white-space': 'nowrap',});

            layerElemCenter(layer_main);

            setStyle(layer_main, {'white-space': '',});
        } else if (options.model === 'confirm') {
            layer_main.classList.add('layer-fixed');

            var confirm = layer_main.getElementsByClassName('layer-confirm')[0];
            layerElemCenter(confirm);
        }

        if (options.zindex) {
            setStyle(layer_main, {'z-index': options.zindex});
        }
    }

    // 4. 添加动画
    Layer.parent.on = function (layer_main) {
        setTimeout(function(){
            layer_main.classList.add('xon');
        }, 1);
    }

    // 5. 后续处理
    Layer.parent.after = function (that, layer_main, options) {
        //短消息,气泡层
        if(options.model === 'msg') {
            // 自动关闭
            that.autoClose();
        } else if (options.model === 'confirm') {
            var colse = layer_main.getElementsByClassName('close')[0],
                btn = layer_main.getElementsByTagName('button');
            addEvent(colse, 'click', function() {
                that.close();
            });
            addEvent(btn[0], 'click', function() {
                that.yes ? that.yes() : '';
                that.close();
            });
            addEvent(btn[1], 'click', function() {
                that.cancel ? that.cancel() : '';
                that.close();
            });
        }
    }

    // 自动关闭
    Layer.parent.autoClose = function () {
        var that = this,
            options = that.options,
            layer_main = that.layer_main;

        // 倒计时
        if (layer_main.getElementsByClassName('layer_times')[0]) {}else{
            var time = options.time;
            if(time && time !== 0){
                setTimeout(function(){
                    that.close();
                }, time * 1000);
            }
        }
    }

    // close
    Layer.parent.close = function (close_id) {
        var that = this,
            options = that.options,
            check_lock = false;

        if (close_id) {}else{
            var layer_main = that.layer_main;
            if(options.lock === true){
                check_lock = true;
            }
        }

        if(!layer_main){
            return false;
        }

        // 移除元素
        layer_main.classList.remove('xon');
        setTimeout(function(){
            var parent_layer_main = layer_main.parentNode;
            if(parent_layer_main){
                parent_layer_main.removeChild(layer_main);
            }
            that.end && that.end();
        }, 201);
    }

    // Layer.parent.xcstrRep = function(str){
    //     str = str.replace(/[\s\n\r]/g,''); //空格换行回车
    //     str = encodeURIComponent(str).toLowerCase();

    //     var reparr = [
    //         [/true/g,'1'],
    //         [/false/g,'0'],
    //         [/%/g,''],
    //         [/\(/g,''],
    //         [/\)/g,''],
    //         [/open/g,'o'],
    //         [/ready/g,'r'],
    //         [/noready/g,'n'],
    //         [/url/g,'u'],
    //         [/html/g,'h'],
    //         [/photo/g,'p'],
    //         [/function/g,'f'],
    //         [/99999/g,'9']
    //     ];
    //     for(var i=0; i<reparr.length; i++){
    //         str = str.replace(reparr[i][0], reparr[i][1]);
    //     }

    //     return str;
    // };

    // 将 layer 绑定到 window
    window.layer = {
        version: '1.0.0',

        // msg
        msg: function(content, options = {}, end = null) {
            var options = {
                model: 'msg',
                content: content,
                time: options.time ? options.time : 1,
                type: options.type ? options.type : 1,
                offset: options.offset ? options.offset : 'middle',
                icon: options.icon ? options.icon : 0,
                zindex: options.zindex ? options.zindex : 99999,
            };
            if (end) {
                options['end'] = end;
            }
            return(this.run(options));
        },

        // confirm
        confirm: function(content, options = {}, yes = null, cancel = null) {
            var options = {
                model: 'confirm',
                title: options.title ? options.title : '信息',
                content: content,
                btn: options.btn ? options.btn : '',
                offset: options.offset ? options.offset : 'middle',
                zindex: options.zindex ? options.zindex : 99999,
            };
            if (yes) {
                options['yes'] = yes;
            }
            if (cancel) {
                options['cancel'] = cancel;
            }
            return(this.run(options));
        },

        // open
        open: function (options) {
            var options = {
                model: 'open',
                type: options.type ? options.type : 1,
                title: options.title ? options.title : 'open elem',
                content: options.content ? options.content : '',
                area: options.area ? options.area : '',
                shadeClose: options.shadeClose ? options.shadeClose : true,
                shade: options.shade ? options.shade : 0.5,
                zindex: options.zindex ? options.zindex : 99999,
            };
            return(this.run(options));
        },

        //核心方法
        run: function(options){
            var x = new Layer(options);
            return x.mainid;
        },
    };
}(window, 'css/layer.css'));
